//
//  MusicTools.swift
//  Ios项目forQQ音乐
//
//  Created by Ann on 2017/9/21.
//  Copyright © 2017年 Ann. All rights reserved.
//

import Foundation

//3.2 创建音乐播放工具类，引入AVFoundation头文件

import AVFoundation
class MusicTools{
    
      var player :AVAudioPlayer?
    
    //3.2.1 创建类单例
    static let sharePlayer: MusicTools = {
        
        let player =  MusicTools()
        
        return player
    }()
    
    //3.2.2 播放音乐通过名字
    func playMusic(musicName:String){
        
        guard let pathURL = Bundle.main.url(forResource: musicName, withExtension: nil) else {
            print("no this MusicName")
            return
        }
        
        if pathURL == player?.url {
            player?.play()
            return
        }
        //磁盘加载音频
        guard let musicTrue = try? AVAudioPlayer(contentsOf: pathURL) else {
            return
        }
       player = musicTrue
        
       player?.play()
    }
    //3.2.3 音频暂停
    func pausePlayer(){
        player?.pause()
    }
    
}
extension MusicTools{
    //4.1 获取歌曲总长度
    func getDuration() -> TimeInterval {
        return  player?.duration ?? 0
    }
    //4.2 获取当前播放时间
    func getCurrentTime() -> TimeInterval{
        
        return  player?.currentTime ?? 0
        
    }
    //4.3 设置从当前时间开始播放
    func setPlayCurrentTime(ct:TimeInterval){
        
      player?.currentTime = ct
    }
    
    
    //代理
    func delegateOfAVAudioPlayerDelegate(delegate:AVAudioPlayerDelegate){
        
         player?.delegate = delegate
        
    }
    
    
    
    
    
}
